package com.ruoyi.media.mediaAccount.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.media.accountGroup.domain.MediaAccountGroup;
import com.ruoyi.media.accountGroup.mapper.MediaAccountGroupMapper;
import com.ruoyi.media.accountGroup.service.IMediaAccountGroupService;
import com.ruoyi.media.forestApi.common.ChannelsApiRequest;
import com.ruoyi.media.mediaAccount.domain.MediaAccount;
import com.ruoyi.media.mediaAccount.domain.bo.MediaAccountBo;
import com.ruoyi.media.mediaAccount.domain.vo.MediaAccountVo;
import com.ruoyi.media.mediaAccount.mapper.MediaAccountMapper;
import com.ruoyi.media.mediaAccount.service.IMediaAccountService;
import com.ruoyi.media.publishModelConfig.service.IMediaPublishModelConfigService;
import com.ruoyi.media.threadConfig.ThreadPoolTaskConfig;
import com.ruoyi.media.utils.WxUtils;
import com.ruoyi.media.utils.XStringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.*;


/**
 * 自媒体账号列Service业务层处理
 *
 * @author dqw
 * @date 2023-03-23
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class MediaAccountServiceImpl extends ServiceImpl<MediaAccountMapper,MediaAccount> implements IMediaAccountService {

    private final MediaAccountMapper baseMapper;

    private final ChannelsApiRequest channelsApiRequest;
    private final IMediaPublishModelConfigService mediaPublishModelConfigService;
    private final MediaAccountGroupMapper mediaAccountGroupMapper;


    /**
     * 查询自媒体账号列
     */
    @Override
    public MediaAccountVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询自媒体账号列列表
     */
    @Override
    public TableDataInfo<MediaAccountVo> queryPageList(MediaAccountBo bo, PageQuery pageQuery) {
        LoginUser loginUser = LoginHelper.getLoginUser(); //获取当前登录用户信息
        LambdaQueryWrapper<MediaAccount> lqw = buildQueryWrapper(bo);
        if(loginUser != null){
            //判断是否下级用户 下级用户查询关联id
            if(loginUser.getUserRank() == 2){
                lqw.eq(MediaAccount::getLowerUserId,loginUser.getUserId());
            }
            else{
                lqw.eq(!loginUser.getUsername().equals("admin"),MediaAccount::getCreateBy,loginUser.getUsername());
            }
            Page<MediaAccountVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
//            List<MediaAccountVo> mediaAccountVos = result.getRecords(); //获取对应数据一并返回对应模板
//            for(MediaAccountVo item: mediaAccountVos){
               // item.setMediaPublishModelConfig(mediaPublishModelConfigService.getById(item.getId()));
//            }
            return TableDataInfo.build(result);
        }
        return TableDataInfo.build();
    }




    /**
     * 查询自媒体账号列列表
     */
    @Override
    public List<MediaAccountVo> queryList(MediaAccountBo bo) {
        LambdaQueryWrapper<MediaAccount> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }





    private LambdaQueryWrapper<MediaAccount> buildQueryWrapper(MediaAccountBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<MediaAccount> lqw = Wrappers.lambdaQuery();
        lqw.orderByDesc(MediaAccount::getLastScanTime);
        lqw.eq(MediaAccount::getDelFlag,0);
        lqw.eq(bo.getDeptId() != null, MediaAccount::getDeptId, bo.getDeptId());
        lqw.eq(bo.getUserId() != null, MediaAccount::getUserId, bo.getUserId());
        lqw.eq(bo.getPlatformCode() != null, MediaAccount::getPlatformCode, bo.getPlatformCode());
        lqw.eq(StringUtils.isNotBlank(bo.getLogo()), MediaAccount::getLogo, bo.getLogo());
        lqw.eq(StringUtils.isNotBlank(bo.getGroupId()), MediaAccount::getGroupId, bo.getGroupId());
        lqw.like(StringUtils.isNotBlank(bo.getNickname()), MediaAccount::getNickname, bo.getNickname());
        lqw.like(StringUtils.isNotBlank(bo.getGroupName()), MediaAccount::getGroupName, bo.getGroupName());
        lqw.eq(StringUtils.isNotBlank(bo.getHeadImgUrl()), MediaAccount::getHeadImgUrl, bo.getHeadImgUrl());
        lqw.eq(StringUtils.isNotBlank(bo.getCookies()), MediaAccount::getCookies, bo.getCookies());
        lqw.eq(bo.getLoginStatus() != null, MediaAccount::getLoginStatus, bo.getLoginStatus());
        lqw.eq(bo.getLastScanTime() != null, MediaAccount::getLastScanTime, bo.getLastScanTime());
        lqw.eq(bo.getAcctType() != null, MediaAccount::getAcctType, bo.getAcctType());
        lqw.eq(StringUtils.isNotBlank(bo.getScanRandom()), MediaAccount::getScanRandom, bo.getScanRandom());
        return lqw;
    }

    /**
     * 新增自媒体账号列
     */
    @Override
    public Boolean insertByBo(MediaAccountBo bo) {
        MediaAccount add = BeanUtil.toBean(bo, MediaAccount.class);
        validEntityBeforeSave(add);
        if(XStringUtils.isEmpty(bo.getCookies())){
            throw new RuntimeException("当前登录参数异常！");
        }
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改自媒体账号列
     */
    @Override
    public Boolean updateByBo(MediaAccountBo bo) {
        if(bo.getIdList() != null){
            List<Long> ids =  Arrays.asList(bo.getIdList());
            LoginUser loginUser =  LoginHelper.getLoginUser();
            for(Long id : ids){
                MediaAccount update = BeanUtil.toBean(bo, MediaAccount.class);
                List<MediaAccountGroup> mediaAccountGroupList =  mediaAccountGroupMapper.getAccountDataByTitle(loginUser.getUserId(),bo.getGroupName());
                update.setId(id);
                update.setGroupId(mediaAccountGroupList.get(0).getId());
                baseMapper.updateById(update);
            }
        }else{
            bo.setId(bo.getId());
            bo.setLoginStatus(1);
            bo.setLastScanTime(new Date());
            MediaAccount update = BeanUtil.toBean(bo, MediaAccount.class);
            baseMapper.updateById(update);
        }
        return true;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(MediaAccount entity){
        //TODO 做一些数据校验,如唯一约束
        LoginUser loginUser =  LoginHelper.getLoginUser();
        entity.setUserId(loginUser.getUserId());
        entity.setDeptId(loginUser.getDeptId());
    }

    /**
     * 批量删除自媒体账号列
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }


    /**
     * 扫码添加账号逻辑
     *
     * @return
     */
    @Override
    public Boolean addMediaAccount(MediaAccountBo bo) {
        //查询是否有该账号
        LoginUser loginUser = LoginHelper.getLoginUser();
        String id = baseMapper.selectAccountByUser(loginUser.getUsername(),bo.getSystemUniqId());
        //自媒体账号参数接收类  添加默认参数
        bo.setLoginStatus(1);
        bo.setLastScanTime(new Date());
        MediaAccount mediaAccount = BeanUtil.copyProperties(bo,MediaAccount.class);
        mediaAccount.setUserId(loginUser.getUserId());
        mediaAccount.setDeptId(loginUser.getDeptId());
        if(StringUtils.isNotEmpty(id)){
            mediaAccount.setId(Long.parseLong(id));
            updateById(mediaAccount);
        }else{
            save(mediaAccount);
        }
        return true;
    }


    /**
     * 根据用户id获取账号信息
     * @param userId
     * @return
     */
    @Override
    public List<MediaAccount> getAccountDataByUserId(String userId) {
        LambdaQueryWrapper<MediaAccount> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MediaAccount::getUserId,userId);
        return list(queryWrapper);
    }


    /**
     * 视频号账号保持登录状态
     */
    @Override
    public void keepChannelsKeepLogin() {
        List<MediaAccount> mediaAccountList = baseMapper.keepLoginAccount();
        ThreadPoolTaskConfig threadPoolTaskConfig = new ThreadPoolTaskConfig();
        ThreadPoolTaskExecutor threadPoolTaskExecutor =  threadPoolTaskConfig.getAsyncExecutor();
        for(MediaAccount item : mediaAccountList){
            threadPoolTaskExecutor.execute(()->{
                String cookies = WxUtils.getChannelsCookie(item.getCookies());
                String resData = channelsApiRequest.authSetFinder(item.getFinderUserName(),cookies);
                if(XStringUtils.isNotEmpty(resData)){
                    //视频号登录需要做日志记录
                    JSONObject resJson = JSONObject.parseObject(resData);
                    if(resJson.getInteger("errCode") == 0){  //账号在线

                        String rawKeyBuff = resJson.getJSONObject("data").getString("rawKeyBuff");
                        Map<String,Object> childrenParams = new HashMap<String,Object>(){
                            {
                                put("pluginSessionId",null);
                                put("rawKeyBuff",rawKeyBuff);
                                put("scene",1);
                                put("timestamp", Calendar.getInstance().getTimeInMillis());
                                put("_log_finder_id",item.getFinderUserName());
                            }
                        };
                        //请求一次数据以保证账号在线状态
                        channelsApiRequest.queryAuthData(item.getFinderUserName(),rawKeyBuff,cookies);
                    }else{

                        int lostAccountNum =  baseMapper.updateLoginStatusByScanRandom(item.getScanRandom());
                        log.info("掉线账号数量：" + lostAccountNum);
                    }
                }
            });
        }
    }
}
